<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0                                                         |
// +------------------------------------------------------------------------+
// | Author: niuzhixin@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
namespace AuctionAppApi\Controller;

use AuctionAppApi\Service\ThriftBailService;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarDealer\Recharge;
use AuctionCore\CarResource\CarModel;
use AuctionCore\CarResource\DealerRepairPayLog;
use AuctionCore\CarResource\ThirdRepairLog;
use AuctionCore\Common\AntNest;
use AuctionCore\Common\PhpRedis;
use AuctionCore\System\AppDevice;
use Think\Controller;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\System\AuctionException;
use AuctionAppApi\Service\RepairService;
use AuctionCore\System\SystemConf;
use AuctionCore\CarResource\DealerRepairLog;
use AuctionCore\CarResource\CarRepairInfo;
use Think\Log;

class RepairController extends BaseController
{
    public $repair = null;

    /** 单次报告单价
     * @var bool|mixed
     */
    protected $single_price;

    /**授信额度
     * @var bool|mixed
     */
    protected $credit_lines;

    /** 车商详情
     * @var
     */
    protected $dealer_detail;

    public function __construct()
    {
        $this->h5_actions = array(
            'C_REPAIR|A_REPAIR_DETAIL'
        );
        parent::__construct();
        $dealer = new Dealer($this->dealer_id);
        $this->dealer_detail = $dealer->dealer_base_info();
        $this->pay_search_key = 'REDIS_PAY_SEARCH_KEY';
        //获取基本配置
        $this->single_price = SystemConf::getConfByName("REPAIR_SINGL_PRICE");
        $this->credit_lines = SystemConf::getConfByName("REPAIR_CREDIT_LINES");
        $this->notify_cbs_key = 'THIRD_REPAIR_NOTIFY_CBS';
        $this->notify_cjd_key = 'THIRD_REPAIR_NOTIFY_CJD';
    }


    /**
     * 维修保养查询表
     */
    public function repair_list(){
        $page = I('post.page','1');
        $page_size = I('post.page_size','20');
        $repair_logs = new DealerRepairLog($this->dealer_id);
        $total = $repair_logs->get_count();
        $total = $total['total'];
        $list = $repair_logs->get_logs($page,$page_size);
        $time =  time();
        foreach($list as $key=>$value){
            $list[$key]['order_id'] = '';
            $list[$key]['pre_time'] ='';
            $list[$key]['pay_state_info'] =  empty($value['pay_state'])?'未结算'.$this->single_price['value'].'元':'已结算'.$this->single_price['value'].'元';
            if(!empty($value['car_id'])){
                $order = $repair_logs->get_order_by_carid($value['car_id']);
                $list[$key]['order_id'] = empty($order['order_id'])?'':$order['order_id'];
                if($list[$key]['order_id']){
                    $cm = new CarModel();
                    $series= $cm->get_series_by_brand($value['brand_id']);
                    $list[$key]['manufacturer']  .= $series['name'];
                }
            }else{
                $list[$key]['car_id'] = '';
            }
            if($value['search_state']==1){
                if( ($time-(strtotime($value['createtime'])))>300){
                    $list[$key]['pre_time'] ='';
                }else{
                    $list[$key]['pre_time'] ='预计'.date('m-d H:i',strtotime($value['createtime'])+300).'生成';
                }
            }
            $list[$key]['createtime'] = time_tran($value['createtime']);
            $list[$key]['manufacturer'] = empty($value['manufacturer'])?'':$list[$key]['manufacturer'];
        }
        $data['currentpage'] = $page;
        $data['pagesize'] = $page_size;
        $data['maxcount'] = $total;
        $data['maxpage'] = ceil($total/$page_size);
        $data['list'] = $list;
        $this->api_200($data);
    }

    /**
     * 透支详情页
     */
    public function credit_list(){
        $page = I('post.page','1');
        $page_size = I('post.page_size','20');
        $data = array();
        //$data['minus_amount'] = $this->dealer_detail['minus_amount'];
        $repair_log = new DealerRepairLog($this->dealer_id);
        $unpaid_logs = $repair_log->get_unpaid_log();
        $data['unpaid_info'] = $unpaid_logs;
        $data['unpaid_info']['minus_amount']= intval($this->dealer_detail['minus_amount']);
        //获取已结算列表分页
        $pay_repair_log = new DealerRepairPayLog($this->dealer_id);
        $list = $pay_repair_log->get_pay_logs($page,$page_size);
        $total = $pay_repair_log->get_count();
        $data['pay_amount'] = $total['pay_amount'];
        $data['currentpage'] = $page;
        $data['pagesize'] = $page_size;
        $data['maxcount'] = $total['total'];
        $data['maxpage'] = ceil($total['total']/$page_size);
        $data['list'] = $list;
        $this->api_200($data);
    }


    /**
     * 查询
     * @throws AuctionException
     */
    public function pay_repair(){
        $vin = I('post.vin');
        if(empty($vin)){
            AuctionException::make_throw("8000105");
        }
        $credit_lines = $this->credit_lines['value'];   //规定透支金额
        $minus_amount = $this->dealer_detail['minus_amount'];   //当前车商已使用透支金额
        $single_price =$this->single_price['value'];            //单次价格
        $bail_amount = $this->dealer_detail['bail_amount'];     //保证金金额
        $is_recharge = Recharge::getLogByDealerId($this->dealer_id);
        if(!$is_recharge){
            AuctionException::make_throw('8000100');
        }
        $repair_log = new DealerRepairLog($this->dealer_id);
        $nums = $repair_log->get_dealer_search_credit();
        if(($nums+($minus_amount/$single_price))>=($credit_lines/$single_price)){
            AuctionException::make_throw('8000107');
        }

        //透支额度减去已透支额度  小于 单次时  查询可用保证金
        if( ($credit_lines-$minus_amount)<$single_price){
            AuctionException::make_throw('8000100');
        }else{
            if($credit_lines<=($minus_amount+$single_price) && $bail_amount>=$credit_lines){
                $this->public_search($vin,1,0);
            }elseif($credit_lines<=($minus_amount+$single_price) && $bail_amount<$credit_lines){
                $this->public_search($vin,1,1);
            }else{
                $this->public_search($vin,0,0);
            }

        }
    }

    /**公用查询判断
     * @param $vin
     * @param $is_bill
     * @throws AuctionException
     */
    private function public_search($vin,$is_bill,$credit){
        $repair_log = new DealerRepairLog($this->dealer_id);
        $is_searching = $repair_log->get_log_by_vin($vin);
        if(empty($is_searching)){
            $option = array(
                'vin'=>$vin,
                'dealer_id'=>$this->dealer_id,
                'createtime'=>date('Y-m-d H:i:s'),
            );
            $log_id = $repair_log->save_log($option);
        }else{
            $log_id = $is_searching['id'];
        }
        info_log('pay_search',array('from'=>'app','log_id'=>$log_id));
        $ant = new AntNest();
        $option = array(
            'vin'         => $vin,
            'callbackurl' => 'http://www.lpaiche.com/Repair/notify?log_id='.$log_id.'&is_bill='.$is_bill.'&credit='.$credit.'&dealer_id='.$this->dealer_id.'&vin='.$vin,
        );
        //获取报告
        $redis = new PhpRedis();
        $arr = ['dealer_id'=>$this->dealer_id,'vin'=>$vin];
        $keyName = getRedisKeyByCode('REDIS_KEY','100037',$arr);
        $redis->set($keyName,time(),86400); //记录查询开始时间
        $state = $ant->getRepairReport($option);
        /**错误状态**/
        if($state['code'] == '900024'){
            $state = $repair_log->update_by_id($log_id,array('price'=>$this->single_price['value'],'search_state'=>3));
            if($state['data']['state'] == '900026'){
                exit(json_encode(array('code' => 500, 'msg' => '暂不支持此品牌查询')));
            } elseif($state['data']['state'] == '900027') {
                exit(json_encode(array('code' => 500, 'msg' => '该VIN码无效')));
            } else {
                echo json_encode(array('code' => 500, 'msg' => '查询失败，本次不扣费','data'=>$state));
            }
            echo json_encode(array('code' => 500, 'msg' => '查询失败，本次不扣费','data'=>$state));
        }elseif($state['code'] == '000000' && $state['data']['state'] == '302'){
            /**查询状态**/
            $repair_log->update_by_id($log_id,array('price'=>$this->single_price['value'],'search_state'=>1));
            exit(json_encode(array('code' => 302, 'msg' => '车辆报告查询中，请稍后查看','data'=>'')));
        }elseif($state['data']['rid']){
            /**成功状态**/
            Log::record('rid='.$state['data']['rid'].'\n\n\n\n---APP----\n\n\n\n','INFO');
            $params = $this->pay_search($state['data'],$log_id,$vin,$is_bill,$credit);
            echo json_encode($params);
        }
    }

    //维保查询支付
    public function pay_search($state,$log_id,$vin,$is_bill,$credit){
        $repair_log = new DealerRepairLog($this->dealer_id);
        $search_state = 2;
        $use_type = 8;
        M()->startTrans();
        $single_price = $this->single_price['value'];
        $minus_amount = $this->dealer_detail['minus_amount'];
        //执行扣钱操作
        $dealer = new Dealer($this->dealer_id);
        $amount = $minus_amount+$single_price;
        $repair_state = $repair_log->update_by_id($log_id,array('price'=>$single_price,'rid'=>$state['rid'],'search_state'=>$search_state,'pay_state'=>0,'manufacturer'=>$state['manufacturer'],'build_time'=>date('Y-m-d H:i:s'),'type'=>$state['third_party'],'brand'=>$state['brand'],'series_model'=>$state['model']));
        $pay_state = $dealer_state =  $clear_state =  $dealer_bail= $bail_log =true;

        $bail_amount = $this->dealer_detail['bail_amount']-$amount;
        if($this->dealer_detail['bail_amount'] < $single_price){
            $is_bill = false;
        }

        if($is_bill){
            $last_amount =  $log_list =0;
            $usemoney = $amount;
            if($credit){
                $log_list = intval($this->dealer_detail['bail_amount']/$single_price);
                $bail_amount = intval(fmod(floatval($this->dealer_detail['bail_amount']),$single_price));
                $last_amount = $amount-($single_price*$log_list);
                $usemoney = $this->dealer_detail['bail_amount']-$bail_amount;
            }
            $collection_no  = genBillsNo('SK',9);
            $colle_state = AssetCenter::collection_log($collection_no,$amount,9);

            $pay_log = new DealerRepairPayLog($this->dealer_id);
            $bail = new ThriftBailService();
            $bail_state = $bail->decBail($this->dealer_id,$usemoney,$use_type,'查询维修保养扣款',0,0,0,$colle_state);
            if($bail_state->code !='000000'){
                M()->rollback();
                return array('code' => 500, 'msg' => '查询失败');
            }
            $bail_log =  AssetCenter::last_bail_log($this->dealer_id,$usemoney,$use_type);//获取最新日志log
            $dealer->edit(array('minus_amount'=>$last_amount)); //修改用户授权额度

            if($credit){
                $pay_state = $pay_log->the_bill($usemoney,$bail_log,$colle_state,$log_list);  //结算操作
            }else{
                $pay_state = $pay_log->the_bill($usemoney,$bail_log,$colle_state);  //结算操作
            }
        }else{
            $dealer_state = $dealer->edit(array('minus_amount'=>$amount));
        }
        if($dealer_state && $repair_state && $pay_state  && $bail_log){
            M()->commit();
        }else{
            M()->rollback();
            return array('code' => 500, 'msg' => '查询失败');
        }
        return array('code' => 200, 'msg' => '查询成功');
    }

    /**
     * 查询当前vin码与车商维保关联状态
     */
    public function repair_status(){
        $vin = I('post.vin');
        $repair_log = new DealerRepairLog($this->dealer_id);
        $dealer_repair =  $repair_log->get_log_by_dealer($vin);
        $data = array(
            'status'=>5,
            'rid'=>0
        );
        if($dealer_repair){
            switch($dealer_repair['search_state']){
                case 1:
                    $data['status'] = 1;
                    break;
                case 2:
                    $data['status'] = 2;
                    $data['rid'] = $dealer_repair['rid'];
                    break;
                case 3:
                    $data['status'] = 3;
                    break;
            }
            $this->api_200($data);
        }else{
            $this->api_200($data);
        }
    }

    /**
     * 查询banner
     */
    public function repair_banner(){
        $data = array(
            array(
                'type'=>3,
                'img'=>'http://img7.isou365.cn/head/2016-11-03/b9c3/1065/314eaba9-662c-d562-6449-7b99de80f1f2.png',
            ),
        );
        $this->api_200($data);
    }

    //维修保养记录详情
    public function repair_detail(){
        $rid = trim(I('get.rid'));
        $repair = new CarRepairInfo($rid);
        $info = $repair->checkRepairLog($rid,$this->dealer_id);
        if(!$info){
            exit(json_encode(array('code' => 500, 'msg' => '抱歉,该RID无效')));
        }
        $ant = new AntNest();
        $option = array(
            'reportId' => $rid
        );
        $data = $ant->getRepairDetail($option);
        $createtime = $repair->get_end_createtime($this->dealer_id);
        if(empty($data)){
            AuctionException::make_throw('8000001');
        }
        $data['introduction']['manufacturer_1'] = $data['introduction']['manufacturer'];
        $data['introduction']['manufacturer'] = $data['introduction']['manufacturer'].' '.$data['introduction']['model'].' '.$data['introduction']['transmissiontype'].' '.$data['introduction']['displacement'];
        $record = $data['normalrepairrecords'];
        $introduction = $data['introduction'];
        $introduction['createtime'] = $createtime;
        $this->assign('record',$record);
        $this->assign('introduction',$introduction);
        $this->display();
    }

    /**
     * 查博士异步通知
     */
    public function NotifyCbs(){
        info_log('Jpush/ansy',array('source'=>'cbs','data'=>$_POST));
        $result = I('post.result');
        $order_id = I('post.orderid');
        $message  = I('post.message');
        if($result && $order_id){
            $redis = new PhpRedis();
            $arr = ['notify_cbs_key'=>$this->notify_cbs_key];
            $keyName = getRedisKeyByCode('REDIS_KEY','100012',$arr);
            $state = $redis->rPush($keyName,json_encode($_POST));
            $return = array("info"=>array('status'=>1,'message'=>'success'));
            if($state){
                exit(json_encode($return));
            }
            $return = array("info"=>array('status'=>2,'message'=>'failed'));
            exit(json_encode($return));
        }else{
            $return = array("info"=>array('status'=>2,'message'=>'failed'));
            exit(json_encode($return));
        }
    }


    /**
     * 车鉴定异步通知
     */
    public function NotifyCjd(){
        info_log('Jpush/ansy',array('source'=>'cjd','data'=>$_POST));
        $order_id = I('post.orderId');
        $vin = I('post.vin');
        $orderStatus = I('post.orderStatus');
        $time = I('post.time');
        $sign = I('post.sign');
        if($order_id && $vin && $orderStatus){
            $redis = new PhpRedis();
            $arr = ['notify_cjd_key'=>$this->notify_cjd_key];
            $keyName = getRedisKeyByCode('REDIS_KEY','',$arr);
            $state = $redis->rPush($keyName,json_encode($_POST));
            $return = array("info"=>array('status'=>1,'message'=>'success'));
            if($state){
                exit(json_encode($return));
            }
        }else{
            $return = array("info"=>array('status'=>2,'message'=>'failed'));
            exit(json_encode($return));
        }


    }
}
?>
